﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using TfsComLib.TfsBranchLib2;
using WpfAdvControls.Component;

namespace TfsBranchLib2.Model
{
    /// <summary>
    ///     Подготовленные данные для просмотра TFS директорий
    /// </summary>
    public class SourceControlFilterMV : ComponentBase
    {
        public SourceControlFilterMV(ISourceControlFilter sourceControlFilter)
        {
            this.sourceControlFilter = sourceControlFilter;
            sourceControlFilter.BasePath.PropertyChanged += BasePath_PropertyChanged;
            TfsItems = new ObservableCollection<TfsItem>();
        }

        private ISourceControlFilter sourceControlFilter { get; set; }

        public ObservableCollection<TfsItem> TfsItems { get; set; }

        private void BasePath_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            UpdateTreeSource();
        }

        public void UpdateTreeSource()
        {
            try
            {
                TfsItems.Clear();
                TfsItems.Add(TfsItem.CreateTfsItem(
                    sourceControlFilter.BasePath.TfsConnection.GetVersionControlServer(),
                    sourceControlFilter.BasePath.BasePath));
                LoadTfsItemsFromSourceConrolFilter();
            }
            catch (Exception ex)
            {
                SetError(string.Format("Update tree source {0}", ex.Message));
            }
        }

        public void LoadTfsItemsFromSourceConrolFilter()
        {
            if (TfsItems.Count == 0)
                return;
            if (TfsItems.Count > 1)
                throw new Exception("Error loading filter subpaths");
            var root_item = TfsItems[0];
            if (root_item.FullPath != sourceControlFilter.BasePath.BasePath)
                Trace.TraceWarning("Root path of TfsItems ({0}) is not the base path of the filter ({1})",
                    root_item.FullPath, sourceControlFilter.BasePath.BasePath);

            var list = new List<TfsItemExpandHelper>();
            foreach (var path in sourceControlFilter.SubPathList)
            {
                list.Add(new TfsItemExpandHelper(root_item, path));
            }
            do
            {
                var removeList = new List<TfsItemExpandHelper>();
                foreach (var item in list)
                {
                    if (item.ExpandLevel())
                    {
                        removeList.Add(item);
                    }
                }
                removeList.ForEach(it => list.Remove(it));
            } while (list.Count > 0);
        }

        internal void SaveTfsItemsToSourceControlFilter()
        {
            sourceControlFilter.SubPathList.Clear();
            foreach (var item in TfsItems)
            {
                CheckItem(item);
            }
        }

        private void CheckItem(TfsItem item)
        {
            if (item.Checked)
            {
                var subPath = item.FullPath.Substring(sourceControlFilter.BasePath.BasePath.Length + 1);
                sourceControlFilter.SubPathList.Add(subPath);
            }
            else
            {
                if (item.Items != null)
                    foreach (var subItem in item.Items)
                    {
                        CheckItem(subItem as TfsItem);
                    }
            }
        }
    }
}